//
//  BlackBoardViewController.m
//  家校互通
//
//  Created by 姬鑫宇 on 15/5/11.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

#import "BlackBoardViewController.h"
#import "BLStyleOneTableViewCell.h"//小图  图文
#import "BLStyleTwoTableViewCell.h"//文字
#import "BLStyleThreeTableViewCell.h"//大横图  图文
#import "UITableView+FDTemplateLayoutCell.h"
#import "HomeWorkViewController.h"
#import "BLActivityDetailViewController.h"//活动详情
#import "BLActivityZoneViewController.h"//活动专区
#import "PayViewController.h"
#import "CoModel.h"

@interface BlackBoardViewController ()<UIGestureRecognizerDelegate,ConnectControlDelegate>{
    ConnectControl *connectCtr;
}
@property (nonatomic, assign) BOOL cellHeightCacheEnabled;
@property (nonatomic, strong) NSMutableArray *contentArray;
@end

@implementation BlackBoardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    _contentTableView.delegate=self;
    _contentTableView.dataSource=self;
    _contentTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _contentTableView.estimatedRowHeight = 200;
    _contentTableView.fd_debugLogEnabled = YES;
    _contentTableView.scrollsToTop=YES;
    _contentArray=[[NSMutableArray alloc]initWithCapacity:0];
    self.cellHeightCacheEnabled = YES;
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    lpgr.minimumPressDuration = 1.0; //seconds  设置响应时间
    lpgr.delegate=self;
    [_contentTableView addGestureRecognizer:lpgr]; //启用长按事件
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connect) name:@"BLACKBOARDCONNECT" object:nil];
    [self addRefreshViews];
    [self addFooter];
    connectCtr = [ConnectControl showForView:self.view];
    connectCtr.delegate=self;
    
    if (connectCtr.superview!=nil && connectCtr.loading==NO)
    {
        [connectCtr setLoading:YES];
    }
    // Do any additional setup after loading the view.
}
-(void)addFooter
{
     __weak __typeof(self) weakSelf = self;
    self.contentTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf)
        {
            [strongSelf loadDateWithView];
        }
//        [strongSelf.contentTableView.footer endRefreshing];
        // 进入刷新状态后会自动调用这个block
    }];
}
-(void)loadDateWithView
{
    NSInteger pageNumber=_contentArray.count/5;
    
    [CoModel blackboardGetNews:^(BOOL result, NSArray *array, NSError *error) {
        if (result) {
            if (array.count&&_contentArray.count%5==0) {
                [ConnectControl removeFromView:self.view];
                [_contentArray addObjectsFromArray:array];
                [_contentTableView reloadData];
                [_contentTableView.footer endRefreshing];
            }else
            {
                _contentTableView.footer.state=MJRefreshStateNoMoreData;
            }

        }
        
    } withtoken:[DSFUserInfo shareUserInstance].token clazzId:[DSFUserInfo shareUserInstance].clazz_user.clazz.id withPageNumber:pageNumber withPageSize:5];
}
- (void)addRefreshViews
{
    __weak __typeof(self) weakSelf = self;
    [self.contentTableView.header beginRefreshing];
    self.contentTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf)
        {
            [strongSelf connect];
        }
        [weakSelf.contentTableView.header endRefreshing];
        
    }];
    
}

- (void)connect
{
    [CoModel blackboardGetNews:^(BOOL result, NSArray *array, NSError *error) {
        if (result) {
            _contentTableView.footer.state=MJRefreshStateIdle;
            [ConnectControl removeFromView:self.view];
            _contentArray = [NSMutableArray arrayWithArray:array];
            [_contentTableView reloadData];
        }
    } withtoken:[DSFUserInfo shareUserInstance].token clazzId:[DSFUserInfo shareUserInstance].clazz_user.clazz.id withPageNumber:0 withPageSize:5];
}


-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer  //长按响应函数
{
     if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
         CGPoint p = [gestureRecognizer locationInView:_contentTableView];
         NSIndexPath *indexPath = [_contentTableView indexPathForRowAtPoint:p];//获取响应的长按的indexpath
         if (indexPath != nil)
         {
//             NSLog(@"long press on table view at row %@", @(indexPath.row));
             [self becomeFirstResponder];
             UIMenuItem *flag = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(editCellBtnAction:)];
             
             UIMenuItem *approve = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(editCellBtnAction:)];
             
             UIMenuItem *deny =[[UIMenuItem alloc] initWithTitle:@"编辑" action:@selector(editCellBtnAction:)];
             
             UIMenuController *menu = [UIMenuController sharedMenuController];
             
             [menu setMenuItems:[NSArray arrayWithObjects:flag, approve, deny, nil]];
             [menu setTargetRect:[_contentTableView rectForRowAtIndexPath:indexPath] inView:_contentTableView];
             [menu setMenuVisible:YES animated:YES];
         }

         
     }
    
  
    
}
-(BOOL) canBecomeFirstResponder {
    return YES;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(editCellBtnAction:) ){
        return YES;
    }
    return NO;
}
-(void)editCellBtnAction:(id)sender
{
    
}

 #pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_contentArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BlackBoardModel *model = [_contentArray objectAtIndex:indexPath.row];
    if(model.type == kBlackBoardHomeWork)
    {
        BLStyleOneTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"BLStyleOneTableViewCell" forIndexPath:indexPath];
        UIView *selectView=[[UIView alloc]initWithFrame:vCell.frame];
        selectView.backgroundColor=COLOR(240, 240, 240);
        
        vCell.selectedBackgroundView=selectView;
        [vCell setContentOfBlackBoard:model];
        return vCell;
    }
    else if (model.type == kBlackBoardActivity)
    {
        
        BLStyleThreeTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"BLStyleThreeTableViewCell" forIndexPath:indexPath];
        UIView *selectView=[[UIView alloc]initWithFrame:vCell.frame];
        selectView.backgroundColor=COLOR(240, 240, 240);
        [vCell setContentOfBlackBoard:model];
        vCell.selectedBackgroundView=selectView;
        return vCell;
    }
    else
    {
        BLStyleTwoTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"BLStyleTwoTableViewCell" forIndexPath:indexPath];
        UIView *selectView=[[UIView alloc]initWithFrame:vCell.frame];
        selectView.backgroundColor=COLOR(240, 240, 240);
        [vCell setContentOfBlackBoard:model];
        vCell.selectedBackgroundView=selectView;
        return vCell;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return nil;
}
#pragma mark -UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BlackBoardModel *model = [_contentArray objectAtIndex:indexPath.row];
    if(model.type == kBlackBoardHomeWork)
    {
   
        return [tableView fd_heightForCellWithIdentifier:@"BLStyleOneTableViewCell" cacheByIndexPath:indexPath configuration:^(BLStyleOneTableViewCell *vCell) {
            [vCell setContentOfBlackBoard:model];
        }];
        //150
    }
    else if (model.type == kBlackBoardActivity)
    {
        return [tableView fd_heightForCellWithIdentifier:@"BLStyleThreeTableViewCell" cacheByIndexPath:indexPath configuration:^(BLStyleThreeTableViewCell *vCell) {
           [vCell setContentOfBlackBoard:model];
        }];
//        BLStyleThreeTableViewCell *cell = (BLStyleThreeTableViewCell *) [self.contentTableView dequeueReusableCellWithIdentifier:@"BLStyleThreeTableViewCell"];
//        [cell setContentOfBlackBoard:model];
//        CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
//        return size.height +1;
//        return 200;
    }
    else
    {
        return [tableView fd_heightForCellWithIdentifier:@"BLStyleTwoTableViewCell" cacheByIndexPath:indexPath configuration:^(BLStyleTwoTableViewCell *vCell) {
            [vCell setContentOfBlackBoard:model];
        }];
//        return 115;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BlackBoardModel *model = [_contentArray objectAtIndex:indexPath.row];
    if (model.type == kBlackBoardActivity)
    {
        BLActivityZoneViewController *vc = [self.storyboard  instantiateViewControllerWithIdentifier:@"BLActivityZoneViewController"];
        AppDelegate *_appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [_appDelegate.mainViewController.navigationController pushViewController:vc animated:YES];
    }
    else if (model.type == kBlackBoardPay)
    {
        PayViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"PayViewController"];
        vc.title=@"支付";
//        vc.hasPayfees=indexPath.row;
        AppDelegate *_appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [_appDelegate.mainViewController.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        HomeWorkViewController *vc = [self.storyboard  instantiateViewControllerWithIdentifier:@"HomeWorkViewController"];
        if (model.type == kBlackBoardNotice) {
            vc.viewControllerTag=BLViewControllerTagForNotice;
        }else if (model.type == kBlackBoardCommend)
            vc.viewControllerTag=BLViewControllerTagForPraise;
        else if (model.type == kBlackBoardHomeWork)
            vc.viewControllerTag=BLViewControllerTagForHomeWork;
    
        vc.blackboardId = [NSString stringWithFormat:@"%ld",(long)model.id];

        AppDelegate *_appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [_appDelegate.mainViewController.navigationController pushViewController:vc animated:YES];
    }
  [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
